package com.sendpo.zjx.sendpo.fragment.storeallproduce;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.LoginActivity;
import com.sendpo.zjx.sendpo.activity.MerchatsActiveInfoActvitiy;
import com.sendpo.zjx.sendpo.activity.StoreMainAllProduceActivity;
import com.sendpo.zjx.sendpo.domain.MerchatsmianDynimcDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.raphets.roundimageview.RoundImageView;
import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/19.
 */

public class SendActiveFragment extends StoreAllProduceBaseFragment {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    Unbinder unbinder;
    private LinearLayoutManager lm;
    RecylcerAdaper adpater;
    private RecylcerAdaper adpter;
    private int currentlastitem=0;
    public int pagenow=1;
    private boolean lastloading=false;

    @Override
    public View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_sendactive, null);
        ButterKnife.bind(view, mActivity);
        return view;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initData();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void initData(){
        lm=new LinearLayoutManager(mActivity, OrientationHelper.VERTICAL,false);

        recyclerview.setLayoutManager(lm);
      pagenow=1;

        List<User> userList= Xutils.queryAll(mActivity.getApplication(),User.class);
        if(userList==null){
            query(pagenow,mActivity.merchantsId,0);
        }else{
            query(pagenow,mActivity.merchantsId,userList.get(0).getUserId());
        }


    }


    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<MerchatsmianDynimcDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<MerchatsmianDynimcDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_juagesendpo_item, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final MerchatsmianDynimcDomain.DataBean dataBean=dataBeen.get(position);
            ih.all_ll.removeAllViews();
            List<String> imgs = dataBean.getMerchantsDyImgsPath();
            if (imgs != null && imgs.size() != 0) {
                final List<String> ivs_s = new ArrayList<>();
                final List<ImageView> ivs = new ArrayList<>();
                for (String img : imgs) {
                    final ImageView iv = new ImageView(mActivity);
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(100), DensityUtil.dip2px(100));
                    lp.setMargins(0, 0, DensityUtil.dip2px(10), 0);
                    iv.setLayoutParams(lp);
                    iv.setBackgroundColor(getResources().getColor(R.color.default_lightgray));
                    Glide.with(SendActiveFragment.this)
                            .load(img)
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .override(500, 500)
                            .into(iv);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                           mActivity.vImageWatcher.show(iv, ivs, ivs_s);
                        }
                    });
                    ivs.add(iv);
                    ivs_s.add(img);
                    ih.all_ll.addView(iv);
                }
            }
            if(dataBean.isDynamicpraiseState()){
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
            }else{
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);

            }
            ih.goods_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    List<User> userList= Xutils.queryAll(mActivity.getApplication(),User.class);
                    if(userList==null||userList.size()==0){
                        Tools.redirectActivity(mActivity,LoginActivity.class);
                        return;
                    }
                    if(dataBean.isDynamicpraiseState()){
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);
                        dataBean.setDynamicpraiseState(false);
                        int count=Integer.parseInt(ih.goood_tv.getText().toString().trim()+"");
                        count--;
                        ih.goood_tv.setText(count+"");
                        nofocus(userList.get(0).getUserId()+"",dataBean.getDynamicPraiseId()+"");
                    }else{
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
                        dataBean.setDynamicpraiseState(true);
                        int count=Integer.parseInt(ih.goood_tv.getText().toString().trim()+"");
                        count++;
                        ih.goood_tv.setText(count+"");
                        focus(userList.get(0).getUserId()+"",dataBean.getMerchantsDyId()+"");
                    }
                }
            });
            ih.goood_tv.setText(""+dataBean.getDynamicPraiseCount());
            ih.guest_tv.setText(""+dataBean.getGuestcount());
            if(TextUtils.isEmpty(dataBean.getMerchantsAvatarpath())){
                Glide.with(SendActiveFragment.this)
                        .load(""+dataBean.getUserAvatarpath())
                        .asBitmap()
                        .animate(R.anim.fade_in)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                ih.juage_img_iv.setImageBitmap(resource);
                            }
                        });
            }else{
                Glide.with(SendActiveFragment.this)
                        .load(""+dataBean.getMerchantsAvatarpath())
                        .asBitmap()
                        .animate(R.anim.fade_in)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                ih.juage_img_iv.setImageBitmap(resource);
                            }
                        });
            }
            if(TextUtils.isEmpty(dataBean.getMerchantsName())){
                ih.juage_img_tv.setText(""+dataBean.getUserName()+"");
            }else{
                ih.juage_img_tv.setText(""+dataBean.getMerchantsName()+"");
            }

            ih.datetime.setText(""+dataBean.getMerchantsCreatedate());
            ih.area.setText(""+dataBean.getMerchantsArea());
            ih.content.setText(""+dataBean.getMerchantsDyComment());

            ih.juage_img_iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("merchantsId",dataBean.getMerchantsId());
                    Tools.redirectActivity(mActivity,StoreMainAllProduceActivity.class,map);
                }
            });
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("data",dataBean);
                    Tools.redirectActivity(mActivity,MerchatsActiveInfoActvitiy.class,map);
                }
            });
            ih.watchnum.setText(""+dataBean.getMerchantsDyLooknumber());
            //ih.address.setText(""+dataBean.getMerchantsAddress());
            LatLng myselflatLng = new LatLng(mActivity.userLatitude,mActivity.userLongitude );
            LatLng latLng = new LatLng(Double.parseDouble(dataBean.getMerchantsLatitude()),Double.parseDouble(dataBean.getMerchantsLongitude()));
            int distance = (int) AMapUtils.calculateLineDistance(myselflatLng, latLng);
            if (distance == 0) {
                ih.location.setText("就在附近");
            } else if (distance <= 5) {
                ih.location.setText("不足5m");
            } else {
                if(distance>=1000){
                    ih.location.setText("距离" + distance/1000 + "km");
                }else{
                    ih.location.setText("距离" + distance + "m");
                }

            }
        }


        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public LinearLayout all_ll;


            public ImageView goods_iv;

            public RelativeLayout goods_bt;
            public TextView goood_tv;
            public RelativeLayout guest_bt;
            public RelativeLayout watch_bt;
            public TextView guest_tv;
            public CircleImageView juage_img_iv;
            public  TextView juage_img_tv;
            public TextView datetime;
            public TextView location;
            public TextView area;
            public TextView content;
            public TextView watchnum;
            public TextView address;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                address=itemView.findViewById(R.id.address);
                all_ll = itemView.findViewById(R.id.all_ll);
                watchnum=itemView.findViewById(R.id.watchnum);
                goods_iv= itemView.findViewById(R.id.goods_iv);
                goods_bt=itemView.findViewById(R.id.goods_bt);
                goood_tv=itemView.findViewById(R.id.goood_tv);
                guest_bt=itemView.findViewById(R.id.guest_bt);
                watch_bt=itemView.findViewById(R.id.watch_bt);
                guest_tv=itemView.findViewById(R.id.guest_tv);
                juage_img_iv=itemView.findViewById(R.id.juage_img_iv);
                juage_img_tv=itemView.findViewById(R.id.juage_img_tv);
                datetime=itemView.findViewById(R.id.datetime);
                location=itemView.findViewById(R.id.location);
                area=itemView.findViewById(R.id.area);
                content=itemView.findViewById(R.id.content);
                watchnum=itemView.findViewById(R.id.watchnum);
            }
        }

        public void initRefresh(List<MerchatsmianDynimcDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerchatsmianDynimcDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }

        public  void focus(String userId,String merchantsDyId){
            Map<String,String> map=new HashMap<>();
            map.put("userId",""+userId);
            map.put("merchantsDyId",merchantsDyId);
            Xutils.POST(HttpUrl.chantpraiseAdd, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        public  void  nofocus(String userId,String merchantsDyPraiseId){

            Map<String,String> map=new HashMap<>();
            map.put("userId",""+userId);
            map.put("merchantsDyPraiseId",merchantsDyPraiseId);
            Xutils.POST(HttpUrl.chantpraiseDelete, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("*************************"+result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
    }


    public void query(int pagenow, final int merchantsId,final int userId) {
        if(mActivity.swiperefresh!=null){
            mActivity.swiperefresh.setRefreshing(true);
        }
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsId", merchantsId + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.merchantdynmicbusinessById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(mActivity.swiperefresh!=null){
                    mActivity.swiperefresh.setRefreshing(false);
                }
                System.out.println("****************"+result);
                Gson gson = new Gson();
                MerchatsmianDynimcDomain domain = gson.fromJson(result, MerchatsmianDynimcDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(),mActivity));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (SendActiveFragment.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                SendActiveFragment.this.pagenow++;
                                                append(SendActiveFragment.this.pagenow,merchantsId, userId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if(mActivity.swiperefresh!=null){
                    mActivity.swiperefresh.setRefreshing(false);
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow,final int merchantsId,final int userId) {
        lastloading = true;
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsId", merchantsId + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.merchantdynmicbusinessById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading = false;
                Gson gson = new Gson();
                MerchatsmianDynimcDomain domain = gson.fromJson(result, MerchatsmianDynimcDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(),mActivity));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (SendActiveFragment.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                SendActiveFragment.this.pagenow++;
                                                append(SendActiveFragment.this.pagenow,merchantsId, userId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading = false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
